package controller;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.BidsDAO;
import dao.ProductsDAO;
import dao.UsersDAO;
import modal.BidModal;
import modal.ProductModal;
import modal.UserModal;

/**
 * Servlet implementation class ProductController
 */
@WebServlet("/ProductController/*")
public class ProductController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ProductController() {
    	super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doProcess(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doProcess(request,response);
	}
	
	protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.print(request.getPathInfo().substring(1));
		int path= Integer.parseInt(request.getPathInfo().substring(1));
		try {
			
			HttpSession session = request.getSession();
			ProductsDAO pd=new ProductsDAO();
			ProductModal prod = (pd.getProductwithProductId(path));
			pd.disconnnect();
			
			session.setAttribute("prod", prod);

			//get upper side of the page  
			UsersDAO udao=new UsersDAO();
			UserModal seller = udao.getUserwithId(prod.getOwnerId());
			udao.disconnnect();
			System.out.println(seller.getEmail());
			session.setAttribute("sellerEmail", seller.getEmail());
			
			//get table etc. 
			ArrayList<BidModal> bids = new BidsDAO().getBidsOfProductbyId(prod.getProductId()); 
			ArrayList<BidModal> sellerBids = new BidsDAO().getOffersOfProductbyId(prod.getProductId()); 
			if(bids!=null)
			session.setAttribute("bids", bids);
			if(sellerBids!=null)
			session.setAttribute("sellerBids", sellerBids);
			response.sendRedirect("/BidMarket/product.jsp");
//        	request.getRequestDispatcher("/product.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
